System.Array.FindLastIndex 方法 (T[], Int32, Predicate)

方法描述

搜索与由指定谓词定义的条件相匹配的元素,并返回 Array 中从第一个元素到指定索引的元素范围内最后一个匹配项的从零开始的索引。

语法定义(C# System.Array.FindLastIndex 方法 (T[], Int32, Predicate) 的用法)

public static int FindLastIndex(
	T[] array,
	int startIndex,
	Predicate match
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
array T[] 要搜索的从零开始的一维 Array。
startIndex System-Int32 向后搜索的从零开始的起始索引。
match System-Predicate Predicate ,定义要搜索的元素的条件。
返回值 System.Int32 如果找到与 match 定义的条件相匹配的最后一个元素,则为该元素的从零开始的索引;否则为 -1。

提示和注释

在 Array 中从 startIndex 开始向后搜索,并在第一个元素停止搜索。

Predicate 是对方法的委托,如果传递给它的对象与委托中定义的条件匹配,则该方法返回 true。 array 的元素被逐个传递给 Predicate

此方法的运算复杂度为 O(n),其中 n 是从 array 开头到 startIndex 这一范围所包含的元素数目。

System.Array.FindLastIndex 方法 (T[], Int32, Predicate)例子

该方法重载返回 –1,因为在该范围内没有以“saurus”结尾的恐龙名称。

using System;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = { "Compsognathus", 
            "Amargasaurus",   "Oviraptor",      "Velociraptor", 
            "Deinonychus",    "Dilophosaurus",  "Gallimimus", 
            "Triceratops" };

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            "\nArray.FindLastIndex(dinosaurs, EndsWithSaurus): {0}", 
            Array.FindLastIndex(dinosaurs, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindLastIndex(dinosaurs, 4, EndsWithSaurus): {0}",
            Array.FindLastIndex(dinosaurs, 4, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus): {0}",
            Array.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus));
    }

    // Search predicate returns true if a string ends in "saurus".
    private static bool EndsWithSaurus(String s)
    {
        if ((s.Length > 5) && 
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

Array.FindLastIndex(dinosaurs, EndsWithSaurus): 5

Array.FindLastIndex(dinosaurs, 4, EndsWithSaurus): 1

Array.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus): -1
 */

异常

异常 异常描述
ArgumentNullException
  • array 为 null。
  • match 为 null。
ArgumentOutOfRangeException startIndex 超出了 array 的有效索引范围。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。